/*
 *
 * -------------------------------------------------------------------------------------------------
 *                            COPYRIGHT(C) BOCO HEALTH 2016
 * -------------------------------------------------------------------------------------------------
 *
 * =================================================================================================
 *  *HISTORY
 *
 *      Tag                Date            Author           Description
 * =================================================================================================
 *      created            2017/1/17      caodailu        create
 * =================================================================================================
 *
 *
 */

package com.boco.familyuser;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;

import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.wxlib.util.SysUtil;
import com.boco.familyuser.entity.main.UserEntity;
import com.boco.familyuser.utils.IMCustomHelper;
import com.facebook.cache.common.CacheKey;
import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.common.internal.Supplier;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.cache.CountingMemoryCache;
import com.facebook.imagepipeline.cache.ImageCacheStatsTracker;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.TimeZone;

public class App extends MultiDexApplication {
    private static App mInstance;
    public static final String USER_SHARED = "user";//SharedPreferences 的key
    public static final String LOGIN_USER = "saveuser";//SharedPreferences 保存用户的key
    public static final String IM_NAME = "im_name";//SharedPreferences 保存用户IMid的key
    public static final String IM_PASS = "im_pass";//SharedPreferences 保存用户IMpass的key
    public static final String IM_APP_KEY = "23524060";

    public static final int LOADING_DELAY = 600;

    private static YWIMKit ywimKit;

    public static YWIMKit getYwimKit() {
        return ywimKit;
    }

    public static void setYwimKit(YWIMKit ywimKit) {
        App.ywimKit = ywimKit;
    }

    public static CloudPushService pushService;
    private String TAG = "APP";


    public static App getInstance() {
        return mInstance;
    }


    private int appCount = 0;//记录activity状态
    private static YWLoginParam loginParam;//im登录param;
    private UserEntity user;//全局用户

    public UserEntity getUser() {
        return user;
    }

    public void setUser(UserEntity user) {
        this.user = user;
    }

    public static YWLoginParam getLoginParam() {
        return loginParam;
    }

    public static void setLoginParam(YWLoginParam loginParam) {
        App.loginParam = loginParam;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        MultiDex.install(this);
        mInstance = this;
        Logger.init("BOCO")                 // default PRETTYLOGGER or use just init()
                .methodCount(3)                 // default 2
                //.hideThreadInfo()              // default shown
                .logLevel(LogLevel.FULL);        // default LogLevel.FULL ,release NONE

//        Bugtags.start("e0b1fc72a36d8d13b2c7459a4219ee24", this, Bugtags.BTGInvocationEventBubble);

        initCloudChannel(this);

        // 注册方法会自动判断是否支持小米系统推送，如不支持会跳过注册。
//        MiPushRegister.register(this, "2882303761517532812", "5531753297812");
        // 注册方法会自动判断是否支持华为系统推送，如不支持会跳过注册。
        // HuaWeiRegister.register(this);

        //子线程中初始化Fresco
        new Thread(new Runnable() {
            @Override
            public void run() {
                initFresco(getApplicationContext(), 200);
            }
        }).start();

        TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));


//        /**
//         * 小米相关Log
//         */
//        LoggerInterface newLogger = new LoggerInterface() {
//            @Override
//            public void setTag(String tag) {
//                // ignore
//            }
//
//            @Override
//            public void log(String content, Throwable t) {
//                Log.d(TAG, content, t);
//            }
//
//            @Override
//            public void log(String content) {
//                Log.d(TAG, content);
//            }
//        };
//        com.xiaomi.mipush.sdk.Logger.setLogger(this, newLogger);


        //全局监听activity生命周期
        this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                appCount++;
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                appCount--;

                if (appCount == 0) {

                    Logger.e("程序进入后台");
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
        //必须首先执行这部分代码, 如果在":TCMSSevice"进程中，无需进行云旺（OpenIM）和app业务的初始化，以节省内存;
        SysUtil.setApplication(this);
        if (SysUtil.isTCMSServiceProcess(this)) {
            return;
        }
        //第一个参数是Application Context
        //这里的APP_KEY即应用创建时申请的APP_KEY，同时初始化必须是在主进程中
        if (SysUtil.isMainProcess()) {

            IMCustomHelper.initCustom();
            YWAPI.init(this, IM_APP_KEY);

        }

    }


    /**
     * 初始化云推送通道
     *
     * @param applicationContext
     */
    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Logger.e("init cloudchannel success");
                if (null != user && user.getHealthFileCode() != null) {
                    pushService.bindAccount(user.getHealthFileCode(), new CommonCallback() {
                        @Override
                        public void onSuccess(String s) {
                            Logger.e("绑定账户成功");
                        }

                        @Override
                        public void onFailed(String s, String s1) {
                            Logger.e("绑定账户失败！！！");

                        }
                    });
                }
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Logger.e("init cloudchannel failed -- errorcode:" + errorCode + " -- " +
                        "errorMessage:" + errorMessage);
            }
        });
    }


    /**
     * 初始化操作，建议在子线程中进行
     * 添加依赖：
     * compile 'com.facebook.fresco:animated-webp:0.10.0'//加载webp
     * compile 'com.facebook.fresco:animated-gif:0.10.0'//加载gif
     *
     * @param context
     * @param cacheSize
     */
    private void initFresco(final Context context, final int cacheSize) {

        DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(context)
                .setMaxCacheSizeOnLowDiskSpace(cacheSize * 1024 * 1024)//最大缓存
                .setBaseDirectoryName("PHOTO_FRESCO")//子目录
                .setBaseDirectoryPathSupplier(new Supplier<File>() {
                    @Override
                    public File get() {
                        //缓存存到应用本身的缓存文件夹，这样卸载的时候能自动清除，其他清理软件也可以扫面出来
                        return context.getCacheDir();
                    }
                }).build();

        MyImageCacheStatsTracker imageCacheStatsTracker = new MyImageCacheStatsTracker();

        ImagePipelineConfig config = ImagePipelineConfig.newBuilder(context)
                .setMainDiskCacheConfig(diskCacheConfig)
                .setImageCacheStatsTracker(imageCacheStatsTracker)
                //Downsapling，要不要向下采样，处理图片的速度比scaling更快，
                //并且同时支持PNG，JPG以及WEBP格式的图片，与ResizeOptions配合使用
                .setDownsampleEnabled(true)
                .setBitmapsConfig(Bitmap.Config.RGB_565)
                .build();

        Fresco.initialize(context, config);
    }

    class MyImageCacheStatsTracker implements ImageCacheStatsTracker {
        @Override
        public void onBitmapCachePut() {

        }

        @Override
        public void onBitmapCacheHit(CacheKey cacheKey) {

        }


        @Override
        public void onBitmapCacheMiss() {

        }

        @Override
        public void onMemoryCachePut() {

        }

        @Override
        public void onMemoryCacheHit(CacheKey cacheKey) {

        }


        @Override
        public void onMemoryCacheMiss() {

        }

        @Override
        public void onStagingAreaHit(CacheKey cacheKey) {

        }

        @Override
        public void onStagingAreaMiss() {

        }

        @Override
        public void onDiskCacheHit() {

        }

        @Override
        public void onDiskCacheMiss() {

        }

        @Override
        public void onDiskCacheGetFail() {

        }

        @Override
        public void registerBitmapMemoryCache(CountingMemoryCache<?, ?> bitmapMemoryCache) {

        }

        @Override
        public void registerEncodedMemoryCache(CountingMemoryCache<?, ?> encodedMemoryCache) {

        }
    }
}
